from django.shortcuts import render, HttpResponse, redirect, reverse
from django.http.response import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods, require_POST, require_GET
from .models import BlogCategory, Blog, BlogComment
from .forms import PubBlogForm
from django.db.models import Q

# Create your views here.
def index(request):
    blogs = Blog.objects.all()
    return render(request, 'html/index.html', context={"blogs": blogs})

def blog_detail(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Exception as e:
        blog = None
    return render(request, 'html/blog_detail.html', context={'blog': blog})



@login_required
@require_http_methods(['GET', 'POST'])
def pub_blog(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'html/pub_blog.html', context={"categories": categories})
    else:
        form = PubBlogForm(request.POST)
        if form.is_valid():
            try:
                title = form.cleaned_data.get('title')
                content = form.cleaned_data.get('content')
                category_id = form.cleaned_data.get('category')
                blog = Blog.objects.create(title=title,
                                           content=content,
                                           category_id=category_id,
                                           author=request.user)
                return JsonResponse({"code": 200, "message": "博客发布成功！", "data": {"blog_id": blog.id}})
            except Exception as e:
                print(f"创建博客失败：{e}")
                return JsonResponse({"code": 500, "message": "服务器错误，发布失败"})
        else:
            print(form.errors)
            return JsonResponse({"code": 400, "message": "参数错误！"})


@require_POST
@login_required()
def pub_comment(request):
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    BlogComment.objects.create(blog_id=blog_id, content=content, author=request.user)
    # 重新加载博客详情页
    return redirect(reverse("blog:blog_detail", kwargs={'blog_id': blog_id}))


@require_GET
def search(request):
    # /search?q=xxx
    q = request.GET.get('q')
    # 从博客的标题和内容中查找
    blogs = Blog.objects.filter(Q(title__icontains=q)|Q(content__icontains=q))
    return render(request, 'html/index.html', context={"blogs":blogs})


@require_POST
@login_required
def delete_blog(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
        # 检查当前登录用户是否为博客作者
        if blog.author != request.user:
            return JsonResponse({"code": 403, "message": "没有权限删除此博客"})
        # 执行删除
        blog.delete()
        return JsonResponse({"code": 200, "message": "博客删除成功", "data": {"redirect_url": "/"}})
    except Blog.DoesNotExist:
        return JsonResponse({"code": 404, "message": "博客不存在"})
    except Exception as e:
        return JsonResponse({"code": 500, "message": f"删除失败：{str(e)}"})